const CONFIG = require('../../../common/config');
const CODE = require('../../../common/code');
const CommonUtil = require('../../../common/util/CommonUtil');
const FileDownLoader = require('../../../common/util/FileDownLoader');
const FileUpLoader = require('../../../common/util/FileUpLoader');
const async = require('async');
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const superagent = require('superagent');
const uuidV1 = require('uuid').v1;
const greenNodejs = require('./green-nodejs-invoker.js');

const assetUtil = function () {

    function assetUtil() {
    }

    /**
     * 转存图片资源
     *
     * @author 王俊
     * @date 2018-07-19
     *
     * @param {Object} option       请求参数
     * @param {String} option.assetUrl  资源链接
     * @param {Number} [option.type]      资源类型, 暂定: 1, 图片, 默认为1
     * @param {Function} callback  回调函数
     *          error: 转存失败
     *          ossUrl: 转存后的图片字段地址
     */
    assetUtil.convertAssetToOss = function (option, callback) {

        const totalTasks = [];

        // 1. 下载资源
        totalTasks.push(function (callback) {
            const data = {};
            if(!option.assetUrl || option.assetUrl.indexOf('http') !==0) return callback('资源链接有误',data);

            const md5 = crypto.createHash('md5');
            const fileName = md5.update(option.assetUrl).digest('hex');
            data.downloadPath  = path.resolve(__dirname, '../../public/images/'+fileName+'.jpg');
            return callback(null,data);
        });
        // 2. 判断文件是否存在
        totalTasks.push(function (data, callback) {
            if(!data.downloadPath) return callback(null, data);
            fs.exists(data.downloadPath, function (exists) {
                data.needDownload = !exists;
                return callback(null, data);
            })
        });
        // 3. 下载文件
        totalTasks.push(function (data, callback) {
            if(!data.needDownload) return callback(null, data);
            FileDownLoader.download(option.assetUrl, data.downloadPath, function (error, downloadPath) {
                return callback(error, data);
            });
        });
        // 4. 上传到oss拿到新的链接地址
        totalTasks.push(function (data, callback) {
            if(!data.downloadPath) return callback(null, data);
            const obj_key = CommonUtil.getUploadFileName(0,"0");
            const bucket = CONFIG.BUCKET_ITBOUR_USER;
            FileUpLoader.upload(data.downloadPath,obj_key,bucket,function (err,url) {
                if (err){
                    return callback(err,null);
                }
                data.ossUrl = url;
                return callback(null,data);
            })
        });
        // 5. 刪除本地圖片
        totalTasks.push(function (data, callback) {
            if(!data.downloadPath) return callback(null, data);
            fs.unlink(data.downloadPath, function(err) {
                return callback(null,data);
            });
        });

        async.waterfall(totalTasks, function (error, data) {
            if(error) return callback(error);
            return callback(error, data.ossUrl);
        })

    };

    /**
     * 图片鉴黄
     *
     * @author 王俊
     * @date 2018-07-31
     *
     * @param {{Object}} option
     * @param {String} option.url
     * @param {Function} callback
     *                      error
     *                      data: {
     *                          pass: 0/1 是否通过
     *                          msg: 不通过原因
     *                      }
     */
    assetUtil.greenImageAsset = function (option, callback) {

        const accessKeyId = CONFIG.OSS_GREEN_IMAGE.AccessKeyId;
        const accessKeySecret = CONFIG.OSS_GREEN_IMAGE.AccessKeySecret;
        const greenVersion = CONFIG.OSS_GREEN_IMAGE.Version;
        const hostname = CONFIG.OSS_GREEN_IMAGE.Hostname;
        const path = CONFIG.OSS_GREEN_IMAGE.Path;
        const clientInfo = {
            ip:'127.0.0.1'
        };
        // 请求体,根据需要调用相应的算法
        const requestBody = JSON.stringify({
            bizType:'Green',
            scenes:['porn'],
            tasks:[{
                dataId: uuidV1(),
                url: option.url
            }]
        });
        const bizCfg = {
            'accessKeyId' : accessKeyId,
            'accessKeySecret' : accessKeySecret,
            'path' : path,
            'clientInfo' : clientInfo,
            'requestBody' : requestBody,
            'hostname' : hostname,
            'greenVersion' : greenVersion
        };
        greenNodejs(bizCfg, function (response) {
            response = JSON.parse(response);
            // 调用失败, 异常状况
            if(response.code !== 200) {
                return callback(response.msg, null);
            }
            const retData = {
                pass: 1,
                msg: '自动审核通过'
            };
            if(!response.data || !response.data[0] || !response.data[0].results) {
                return callback('鉴黄失败,请稍后重试', null);
            }
            const result = response.data[0].results;
            for (let i=0; i<result.length; i++) {
                const r = result[i];
                // 鉴黄
                if(r.scene === 'porn') {
                    // normal：正常图片，无色情 sexy：性感图片 porn：色情图片
                    if(r.label === 'sexy' || r.label === 'porn') {
                        retData.msg = '图片涉黄, 不予通过';
                        retData.pass = 0;
                        break;
                    }
                }
                if(r.scene === 'terrorism') {
                    // review
                    if(r.suggestion === 'block' || r.suggestion === 'review') {
                        retData.msg = '图片涉嫌暴恐, 不予通过';
                        retData.pass = 0;
                        break;
                    }
                }
            }
            if(CONFIG.DEBUG) {
                console.log(JSON.stringify(response));
            }
            return callback(null, retData);
        });
    };

    return assetUtil;
}();

module.exports = assetUtil;